/* eslint-disable no-use-before-define */
import { Ajax } from "../../lib/ajax.js";
import { xqykjzz } from "./cwbbData.js";
import {
  asyncSetInterval,
  fixZeroInfo,
  currentToTaxindex,
  notifications,
} from "../../lib/zeroReportUtils.js";
import {
  asyncTableStart,
  saveTableDetailXgmnsr,
  startQysdsTableDetail,
} from "./asyncTableDetail.js";

let pages = {
  loginIndex:
    "https://etax.shanghai.chinatax.gov.cn/wszx-web/bszm/apps/views/beforeLogin/indexBefore/pageIndex.html",
  pageIndex:
    "https://etax.shanghai.chinatax.gov.cn/wszx-web/bszm/apps/views/companyPage/desktopTax.html",
  page10:
    "https://etax.shanghai.chinatax.gov.cn/sbzx-web/apps/views/sb_ybnsr_yds/index.html",
  page11:
    "https://etax.shanghai.chinatax.gov.cn/sbzx-web/apps/views/sb_ybnsr_201905/sb_ybnsr.html",
  page20:
    "https://etax.shanghai.chinatax.gov.cn/sbzx-web/apps/views/sb_cwbb_xqy_kjzz/sb_cwbb_xqy_kjzz.html",
  page22:
    "https://etax.shanghai.chinatax.gov.cn/sbzx-web/apps/views/public/sb_success.html",
  page21:
    "https://etax.shanghai.chinatax.gov.cn/sbzx-web/apps/views/sbjgcx/sbjgcx.html",
  // 增值税小规模
  page30:
    "https://etax.shanghai.chinatax.gov.cn/sbzx-web/apps/views/xgmsb-tbs_2019/xgmsb-tbs.html",
  // 企业所得税
  page40:
    "https://etax.shanghai.chinatax.gov.cn/sbzx-web/apps/views/sb_sdsA_yj_new_202006/sb_sdsA_yj_new.html",
  
};
let zzsBaobiao = {};
let zeroInfo;

// 获得公信息
let getCompanyInfo = async () => {
  let url =
    "https://etax.shanghai.chinatax.gov.cn/yhzx-web/api/nsrxx/get?timestamp=" +
    new Date().getTime();
  let data = await Ajax.getPromise({ url });
  if (JSON.parse(data).success) {
    return JSON.parse(data).value.nsrjbxx;
  }
  return false;
};
// 获得列表
let getWsbList = async () => {
  let wsbListUrl =
    "https://etax.shanghai.chinatax.gov.cn/sbzx-web/api/sh/sbtc/cb/queryWsbList";
  let wsbList = await Ajax.postPromise({ url: wsbListUrl });
  if (JSON.parse(wsbList).success) {
    wsbList = JSON.parse(wsbList).value.map((item) => {
      let declareCycle = "month";
      let skssqq = item.skssqz.split("-");
      let skssqz = item.skssqz.split("-");
      if (skssqz[0] !== skssqq[0]) {
        declareCycle = "year";
      } else if (skssqz[1] !== skssqq[1]) {
        declareCycle = "season";
      }
      return {
        declareName: item.zsxmmc,
        accountBook:
          item.skssqz.split("-")[0] + "-" + item.skssqz.split("-")[1],
        declareCycle,
        isSuccess: item.sbztmc === "已申报",
      };
    });
    return wsbList;
  }
  return {};
};
// 输入框搜索
let inputSerch = async (text) => {
  document.querySelector("#keyword").value = text;
  document.querySelector("#search-btn").click();
  let timer = setInterval(() => {
    let lis = $(
      "body > div.layui-layer.layui-layer-dialog.layer-anim > div > div > div.function-all > ul > li > a"
    );
    if (lis.length) {
      clearInterval(timer);
      timer = null;
      let currentLi = Array.from(lis).find((item) =>
        $(item).text().includes(text)
      );
      if (currentLi) currentLi.click();
      document.querySelector("#keyword").value = "";
    }
  }, 500);
};

const closeYd = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      let colseBtns = $(
        "div.mini-panel.mini-window .mini-tools span.mini-tools-close"
      );
      // let colsebtn1 = document.querySelector('.mini-panel.mini-window.mini-panel-collapse > div > div.mini-panel-header > div > div.mini-tools .mini-tools-close ');
      document.querySelector("body > div.closeGuide > .img-guide").click();
      setTimeout(() => {
        document
          .querySelector("body > div.mask-content.sousuo > div.iknow > img")
          .click();
      }, 200);
      // if (colsebtn1) colsebtn1.click();
      if (colseBtns.length) {
        Array.from(colseBtns).forEach((element) => {
          element.click();
        });
      }
      resolve(true);
    }, 2000);
  });
};

let pageIndex = async (currentZeroInfo) => {
  // 引导关闭
  await closeYd();
  let nsrjbxx = await getCompanyInfo();
  let wsbList = await getWsbList();

  let {recordList, customerType, zzsType} = currentZeroInfo;
  let isCwbb = recordList.find(item => item.declareName.includes('小企业会计准则'));
  // 财务报表
  if(customerType.includes('小企业会计准则')) {
    if( !isCwbb || !isCwbb.isSuccess) {
      let text = "财务报表报送与信息采集（小企业会计准则-月季报）";
      await inputSerch(text);
      return;
    }
  } else {
    notifications({ message: '暂不支持企业会计准则的财务报表' });
  }
  // 增值税
  let isZzs = recordList.find(item => item.declareName.includes('增值税'));
  let zzs = wsbList.find(item => item.declareName.includes('增值税'));
  if((!isZzs || !isZzs.isSuccess) && !zzs.isSuccess) {
    if(nsrjbxx.nsrzg.includes('小规模纳税人')){
      let text = "增值税小规模纳税人申报";
      await inputSerch(text);
    }else {
      let text = "增值税一般纳税人云化申报";
      await inputSerch(text);
    }
    return;
  }
  // 企业所得税
  let isQysds = recordList.find(item => item.declareName.includes('企业所得税'));
  let qysds = wsbList.find(item => item.declareName.includes('企业所得税'));
  if((!isQysds || !isQysds.isSuccess) || !qysds.isSuccess ) {
    if(wsbList.find((item) => item.declareName.includes("企业所得税") && !item.isSuccess)) {
      let text = "居民企业（查账征收）企业所得税月（季）度申报";
      await inputSerch(text);
      return;
    }
  }
  // 报税完成
  window.postMessage({
    event: 'zeroReportBack',
    data: {
      ...currentZeroInfo,
      // recordList: recordList.map(item => {
      //   item.isSuccess = false;
      //   return item;
      // })
    }
  });
};

let page10 = async () => {
  window.ydsEntry.go("tbs");
};
let page11 = async () => {
  setTimeout(async () => {
    asyncSetInterval(() => {
      if (
        document.querySelector("#close_btn") &&
        document.querySelector("#close_btn").innerText.includes("我知道了")
      ) {
        window.ybnsr.closeTs();
        if (document.querySelector("#closeZcTip"))
          document.querySelector("#closeZcTip").click();
        saveZzsbaobiao();
        return true;
      }
    }, 2000);
  }, 11000);
};
// 保存报表
let saveZzsbaobiao = async () => {
  let trs = $("#content-table > tbody tr");
  let biTian = Array.from(trs).filter((item) =>
    $(item).find("td.table-needed").text().includes("必填")
  );
  let flzl1 = biTian.find((item) =>
    $(item).find("td.table-name").text().includes("申报表附列资料一")
  );
  let flzl2 = biTian.find((item) =>
    $(item).find("td.table-name").text().includes("申报表附列资料二")
  );
  let flzl3 = biTian.find((item) =>
    $(item).find("td.table-name").text().includes("申报表附列资料三")
  );
  let sbb = biTian.find((item) =>
    $(item)
      .find("td.table-name")
      .text()
      .includes("增值税纳税申报表（一般纳税人适用")
  );
  let fjssb = biTian.find((item) =>
    $(item).find("td.table-name").text().includes("增值税一般纳税人附加税申报")
  );
  // await asyncTableStart();
  if (!zzsBaobiao.flzl1 && flzl1) {
    zzsBaobiao.flzl1 = true;
    await zzsybnslIsReport(flzl1);
  } else if (!zzsBaobiao.flzl2 && flzl2) {
    zzsBaobiao.flzl2 = true;
    zzsybnslIsReport(flzl2);
  } else if (!zzsBaobiao.flzl3 && flzl3) {
    zzsBaobiao.flzl3 = true;
    zzsybnslIsReport(flzl3);
  } else if (sbb && !zzsBaobiao.sbb) {
    zzsBaobiao.sbb = true;
    zzsybnslIsReport(sbb);
  } else if (fjssb && !zzsBaobiao.fjssb) {
    zzsBaobiao.fjssb = true;
    zzsybnslIsReport(fjssb);
  } else {
    await asyncTableStart();
    document.querySelector("#sb_save").click();
    await submitzzs();
  }
};
// 循环
let loopZzs = () => {
  setTimeout(() => {
    saveZzsbaobiao();
  }, 1000);
};
// mini-messagebox
let submitzzs = async () => {
  return asyncSetInterval(() => {
    let subBtn = $(".mini-messagebox a");
    if (subBtn.length) {
      let sBtn = Array.from(subBtn).find((item) =>
        $(item).text().includes("确定")
      );
      if (sBtn) sBtn.click();
      setTimeout(() => {
        document.querySelector("#sb_save").click();
      }, 3000);
    }
  }, 1000);
};
let zzsybnslIsReport = async (flzl1) => {
  if (flzl1 && flzl1.querySelector(".table-operation").innerText === "填写") {
    flzl1.querySelector(".table-operation > .sb_edit").click();
  } else {
    flzl1.querySelector(".table-operation > .sb_reedit").click();
  }
  await saveflzl1();
};

let saveflzl1 = async () => {
  asyncSetInterval(() => {
    let iframe = document.querySelector(
      ".mini-panel.mini-window div.mini-panel-viewport > div.mini-panel-body > iframe"
    );
    if (iframe) {
      return iframe;
    }
  }, 500).then((iframe) => {
    let met = iframe.getAttribute("onload");
    iframe.onload = () => {
      eval(`window.${met}`);
      asyncSetInterval(() => {
        let sb_save = iframe.contentDocument.querySelector("#sb_save");
        let miniMask = document.querySelector(".mini-mask");
        if (sb_save && !miniMask) {
          sb_save.click();
          return true;
        }
      }, 500).then((res) => {
        return asyncSetInterval(() => {
          let btns = iframe.contentDocument.querySelector(".mini-messagebox a");
          let text = iframe.contentDocument.querySelector(
            ".mini-messagebox tbody > tr"
          ).innerText;
          if (btns) {
            if (text.includes("保存成功！")) {
              setTimeout(() => {
                btns.click();
                loopZzs();
              }, 1000);
              return true;
            }
            window.location.reload();
            return false;
          }
        }, 1000);
      });
    };
  });
};

// 财务报表
let page20 = async (currentZeroInfo) => {
  let year = currentZeroInfo.year;
  let month =
    currentZeroInfo.endPeriod > 9
      ? currentZeroInfo.endPeriod
      : "0" + currentZeroInfo.endPeriod;
  document.querySelector("#sbny\\$text").value = year + "" + month;
  setTimeout(() => {
    document.querySelector("#sbny-ok").click();
    setTimeout(() => {
      zcfzbWrite(currentZeroInfo);
    }, 1000);
  }, 500);
};
// 确定按钮
let sureBtn = async (ele, isSure) => {
  return new Promise((resolve) => {
    ele =
      ele ||
      $(
        ".mini-messagebox.mini-panel.mini-window.mini-window-drag .mini-messagebox-buttons .mini-button-text"
      );
    setTimeout(() => {
      if (ele.length) {
        if (isSure) {
          ele[0].click();
        } else {
          Array.from(ele).forEach((item) => {
            item.click();
          });
        }
      }
      resolve(true);
    }, 1000);
  });
};
let zcfzbWrite = async ({ cwbbInfo, customerType }) => {
  await sureBtn();
  await sureBtn();
  let zcfzb = cwbbInfo.zcfzb;
  let systemData = false;
  let shuijuData = false;
  let zcfzbDefault = customerType.includes("小企业会计准则")
    ? xqykjzz.zcfzb
    : "";
  let result = Object.keys(zcfzbDefault).map((key) => {
    let col = zcfzbDefault[key];
    let colValue = zcfzb[col];
    let value =
      key.includes("C") || key.includes("G") ? colValue.qmye : colValue.ncye;
    if (parseFloat(value)) systemData = true;
    if (parseFloat($(`#${key}`).val())) shuijuData = true;
    // $(`#${key}`).val(value || 0.0);
    return {
      key,
      value,
    };
  });
  if (systemData) {
    result.forEach(({ key, value }) => {
      $(`#${key}`).val(value || 0.0);
    });
  } else if (!shuijuData && !systemData) {
    let arr = ["001C9", "001D9", "001H28", "001G28"];
    arr.forEach((item) => {
      $(`#${item}`).val(0.01);
      $(`#${item}`).blur();
    });
  }
  // console.log(result);
  $("#sb_tempSaveCheck").click();
  await sureBtn();
  lrbWrite({ cwbbInfo, customerType });
};
let lrbWrite = async ({ cwbbInfo, customerType }) => {
  $("#mini-2\\$2").click();
  let lrb = cwbbInfo.lrb;
  let lrbDefault = customerType.includes("小企业会计准则") ? xqykjzz.lrb : "";
  let result = Object.keys(lrbDefault).map((key) => {
    let col = lrbDefault[key];
    let colValue = lrb[col];
    let value = key.includes("G") ? colValue.bnljje : colValue.bqje;
    $(`#${key}`).val(value || "0.00");
    return {
      key,
      value,
    };
  });
  console.log(result);
  $("#sb_tempSaveCheck").click();
  await sureBtn();
  xjllbWhite({ cwbbInfo, customerType });
};

let xjllbWhite = async ({ cwbbInfo, customerType }) => {
  $("#mini-2\\$3").click();
  let xjllb = cwbbInfo.xjllb;
  let xjllbDefault = customerType.includes("小企业会计准则")
    ? xqykjzz.xjllb
    : "";
  let result = Object.keys(xjllbDefault).map((key) => {
    let col = xjllbDefault[key];
    let colValue = xjllb[col];
    let value = key.includes("G") ? colValue.bnljje : colValue.bqje;
    $(`#${key}`).val(value || "0.00");
    return {
      key,
      value,
    };
  });
  $("#sb_tempSaveCheck").click();
  await sureBtn();
  document.querySelector("#sb_save").click();
  await sureBtn("", true);
};

let page21 = async (currentZeroInfo) => {
  setTimeout(() => {
    document.querySelector("#search-btn").click();
    asyncSetInterval(() => {
      let trs = $("#mini-grid-table-bodysbjgcx_grid tr.mini-grid-row");
      if (trs.length) {
        let arr = [];
        // 出重 申报成功的
        let list = Array.from(trs).filter((item) => {
          let sText = $(item).find("td:nth-child(7)").text();
          let szText = $(item).find("td:nth-child(2)").text();
          if (sText.includes("申报成功")) {
            arr.push(szText);
            return true;
          }
          return false;
        });
        // 出重失败的
        let list1 = Array.from(trs).filter((item) => {
          let szText = $(item).find("td:nth-child(2)").text();
          if (arr.includes(szText)) return false;
          arr.push(szText);
          return true;
        });
        let recordList = list.concat(list1);
        recordList = recordList.map((item) => {
          let bsssqz = $(item).find("td:nth-child(6)").text().split("-");
          let bsssqs = $(item).find("td:nth-child(5)").text().split("-");
          let month = parseInt(bsssqz[1]) - parseInt(bsssqs[1]);
          return {
            declareName: $(item).find("td:nth-child(2)").text(),
            accountBook: bsssqz[0] + "-" + bsssqz[1],
            declareCycle:
              month === 11 ? "year" : month === 2 ? "season" : "month",
            isSuccess: $(item)
              .find("td:nth-child(7)")
              .text()
              .includes("申报成功"),
          };
        });
        fixZeroInfo({recordList});
        setTimeout(() => {
          currentToTaxindex({isclose: true });
        }, 500);
        return true;
      }
    }, 500);
  }, 2000);
};

let page30 = async () => {
  // 关闭提示
  await closePage30tip();
  await closePage30tip(2);
  await closePage30tip(3);
  let lis = $(
    "#tabs > table > tbody > tr > td:nth-child(2) > div.mini-tabs-scrollCt > div.mini-tabs-headers > table > tbody > tr td"
  );
  let zzsnsssb = Array.from(lis).find((item) =>
    $(item).text().includes("增值税纳税申报表")
  );
  await saveTable(zzsnsssb);
  let flzl = Array.from(lis).find((item) =>
    $(item).text().includes("附列资料")
  );
  if (flzl) await saveTable(flzl);
  let jzmmb = Array.from(lis).find((item) =>
    $(item).text().includes("增值税减免税申报明细表")
  );
  await saveTable(jzmmb);
  let fjs = Array.from(lis).find((item) => $(item).text().includes("附加税"));
  await saveTable(fjs);
  await asyncSetInterval(async () => {
    // 同步明细表
    // let result = await saveTableDetailXgmnsr({ zzsnsssb, flzl, jzmmb, fjs });
    // return result;
    return true;
  }, 1000)
    .then(() => {
      $("#lsb").click();
      return true;
    })
    .then(() => {
      return asyncSetInterval(() => {
        let btns = $(
          ".mini-panel.mini-window.mini-window-drag.mini-messagebox .mini-button"
        );
        if (btns.length > 1) {
          let sure = Array.from(btns).find((item) =>
            $(item).text().includes("确定")
          );
          if (sure) sure.click();
          return true;
        }
      });
    });
};

let page40 = async (currentZeroInfo) => {
  let { quarterSum, endSum } = currentZeroInfo;
  // 处理弹窗
  await qysdsBox2();
  await qysdsBox();
  await qysdsBox1();

  let tabs = $("#tabs div.mini-tabs-scrollCt > div.mini-tabs-headers td");
  let tables = $("table.sb_table");
  // 处理A200000
  await asyncSetInterval(() => {
    let A200000 = Array.from(tabs).find((item) =>
      $(item).text().includes("A200000中华人民共和国企业所得税月")
    );
    let table = Array.from(tables).find((item) =>
      $(item).attr("sb_title").includes("A200000中华人民共和国企业所得税月")
    );
    A200000.click();
    let cyrs = $(table).find("tbody > tr:nth-child(6) > td.enable > input"); // 从业人数
    let zcze = $(table).find("tbody > tr:nth-child(7) > td.enable > input"); // 资产总额
    let cyrsLength = cyrs.length;
    let jczyrs = cyrs[cyrsLength - 2];
    let jmzyrs = cyrs[cyrsLength - 1];
    let jczczz = cyrs[cyrsLength - 2];
    let jmzczz = zcze[cyrsLength - 1];
    if (!parseFloat($(jczyrs).val())) $(jczyrs).val(1);
    if (!parseFloat($(jmzyrs).val())) $(jmzyrs).val(1);
    if (parseFloat(quarterSum)) {
      $(jczczz).val(quarterSum);
    } else if (!parseFloat($(jczczz).val())) {
      $(jczczz).val(0.01);
    }
    if (parseFloat(endSum)) {
      $(jmzczz).val(endSum);
    } else if (!parseFloat($(jmzczz).val())) {
      $(jmzczz).val(0.01);
    }
    let gxjj = Array.from($(table).find("tbody > tr")).find((item) =>
      $(item).find("td:nth-child(1)").text().includes("高新技术企业")
    );
    let input = $(gxjj).find(
      ".enable.txt-l .mini-list-inner > div:nth-child(2) > input"
    );
    Array.from(input).forEach((item) => item.click());
    return true;
  }, 1000)
    .then(() => {
      return asyncSetInterval(() => {
        $("#sb_tempSaveCheck").click();
        return true;
      }, 1000).then(() => {
        return asyncSetInterval(async () => {
          if (
            $(
              ".mini-messagebox.mini-panel.mini-window.mini-window-drag .mini-messagebox-buttons .mini-button-text"
            ).length
          ) {
            await sureBtn();
            return true;
          }
        }, 1000);
      });
    })
    .then(() => {
      let A200000 = Array.from(tabs).find((item) =>
        $(item).text().includes("A201010免税收入")
      );
      A200000.click();
      return asyncSetInterval(() => {
        $("#sb_tempSaveCheck").click();
        return true;
      }, 1000).then(() => {
        return asyncSetInterval(async () => {
          if (
            $(
              ".mini-messagebox.mini-panel.mini-window.mini-window-drag .mini-messagebox-buttons .mini-button-text"
            ).length
          ) {
            await sureBtn();
            return true;
          }
        }, 1000);
      });
    })
    .then(() => {
      let A200000 = Array.from(tabs).find((item) =>
        $(item)
          .text()
          .includes("A201020 资产加速折旧、摊销(扣除)优惠明细表（附表二）")
      );
      A200000.click();
      return asyncSetInterval(() => {
        $("#sb_tempSaveCheck").click();
        return true;
      }, 1000).then(() => {
        return asyncSetInterval(async () => {
          if (
            $(
              ".mini-messagebox.mini-panel.mini-window.mini-window-drag .mini-messagebox-buttons .mini-button-text"
            ).length
          ) {
            await sureBtn();
            return true;
          }
        }, 1000);
      });
    })
    .then(() => {
      let A200000 = Array.from(tabs).find((item) =>
        $(item).text().includes("A201030减免所得税优惠明细表（附表三）")
      );
      A200000.click();
      return asyncSetInterval(() => {
        $("#sb_tempSaveCheck").click();
        return true;
      }, 1000).then(() => {
        return asyncSetInterval(async () => {
          if (
            $(
              ".mini-messagebox.mini-panel.mini-window.mini-window-drag .mini-messagebox-buttons .mini-button-text"
            ).length
          ) {
            await sureBtn();
            return true;
          }
        }, 1000);
      });
    })
    .then(() => {
      let A200000 = Array.from(tabs).find((item) =>
        $(item).text().includes("居民企业参股外国企业信息报告表")
      );
      A200000.click();
      return asyncSetInterval(() => {
        $("#sb_tempSaveCheck").click();
        return true;
      }, 1000).then(() => {
        return asyncSetInterval(async () => {
          if (
            $(
              ".mini-messagebox.mini-panel.mini-window.mini-window-drag .mini-messagebox-buttons .mini-button-text"
            ).length
          ) {
            await sureBtn();
            return true;
          }
        }, 1000);
      });
    })
    .then(async () => {
      // 同步申报表
      // await startQysdsTableDetail({ tabs, tables });
      return asyncSetInterval(() => {
        $('#sb_save').click();
        return true;
      }, 1000)
    }).catch(() =>{
      window.location.onload();
    });
};

let qysdsBox = async () => {
  return asyncSetInterval(() => {
    let iframe = $(
      ".fixedWindowTop0 > div > div.mini-panel-viewport > div.mini-panel-body > iframe"
    );
    if (iframe.length) {
      let iwid = iframe.contents();
      let iread = iwid.find("#read");
      if (iread.length) {
        iread.click();
        return iwid;
      }
    }
  }, 1000)
    .then((iwid) => {
      return asyncSetInterval(() => {
        let inext = iwid.find("#next");
        if (inext.length) {
          inext[0].click();
          return iwid;
        }
      }, 1000);
    })
    .then((iwid) => {
      return asyncSetInterval(() => {
        let iread = iwid.find("#read");
        if (iread.length) {
          iread.click();
          return iwid;
        }
      }, 1000);
    })
    .then((iwid) => {
      return asyncSetInterval(() => {
        let inext = iwid.find("#next");
        if (inext.length) {
          inext[0].click();
          return iwid;
        }
      }, 1000);
    });
};
let qysdsBox1 = async () => {
  let number = 0;
  return asyncSetInterval(() => {
    let btns = $(".mini-messagebox .mini-button");
    let sure = Array.from(btns).find((item) => $(item).text().includes("是"));
    if (sure) {
      sure.click();
      return true;
    }
    if (number > 1) {
      return true;
    }
    number++;
  }, 1000).then(() => {
    let number = 0;
    return asyncSetInterval(() => {
      let btns = $(".mini-messagebox .mini-button");
      let sure = Array.from(btns).find((item) =>
        $(item).text().includes("确定")
      );
      if (sure) {
        sure.click();
        return true;
      }
      if (number > 1) {
        return true;
      }
      number++;
    }, 1000);
  });
};
let qysdsBox2 = async () => {
  let number = 0;
  return asyncSetInterval(() => {
    let btns = $(".mini-messagebox .mini-button");
    let text = $(".mini-messagebox .mini-messagebox-content-text");
    if (
      btns.length &&
      text
        .text()
        .includes(
          "系统检测到您上次填写了申报表，点击确定还原上次填写的数据，点击取消重新填写申报表！"
        )
    ) {
      btns[0].click();
      return true;
    }
    if (number > 2) {
      return true;
    }
    number++;
  });
};

async function saveTable(ele) {
  return asyncSetInterval(() => {
    if (ele && $("#sb_tempSaveCheck").length) {
      ele.click();
      return true;
    }
  }, 1000)
    .then(() => {
      return asyncSetInterval(() => {
        $("#sb_tempSaveCheck").click();
        return true;
      }, 1000);
    })
    .then(() => {
      return asyncSetInterval(() => {
        if (
          $(
            ".mini-messagebox.mini-panel.mini-window.mini-window-drag .mini-messagebox-buttons .mini-button-text"
          ).length
        ) {
          sureBtn();
          return true;
        }
      }, 1000);
    });
}

async function closePage30tip(type) {
  let number = 0;
  return asyncSetInterval(async () => {
    if (type === 2 && window.xgm && window.xgm.close1PercentTip) {
      try {
        window.xgm.close1PercentTip();
      } catch {
        return true;
      }
      return true;
    }
    if (
      $(
        ".mini-messagebox.mini-panel.mini-window.mini-window-drag .mini-messagebox-buttons .mini-button-text"
      ).length
    ) {
      sureBtn();
      return true;
    }
    if (number > 3) {
      return false;
    }
    number++;
  }, 1000);
}

// 零申报
function zeroReprot(currentZeroInfo) {
  let href = window.location.href;
  if (href.includes(pages.pageIndex)) {
    // 首页相关
    pageIndex(currentZeroInfo);
  }
  if (href.includes(pages.page10)) {
    // 一般增值税
    page10();
  }

  // if ()
  if (href.includes(pages.page11)) {
    // 一般增值税
    zzsBaobiao = {
      flzl1: false,
      flzl2: false,
      flzl3: false,
      sbb: false,
      fjssb: false,
    };
    page11();
  }
  // 增值税小规模
  if (href.includes(pages.page30)) {
    page30();
  }
  // 企业所得税
  if (href.includes(pages.page40)) {
    page40(currentZeroInfo);
  }
  if (href.includes(pages.page20)) {
    // 财务报表
    page20(currentZeroInfo);
  }
  // 结果页
  if (href.includes(pages.page21)) {
    page21(currentZeroInfo);
  }
  // if (href.includes(pages.page22)) {
  //   let referrer = document.referrer;
  //   let type = "cwbb";
  //   if (referrer.includes(pages.page10)) {
  //     type = "zzsybnsr";
  //   }
  //   setTimeout(() => {
  //     currentToTaxindex({
  //       isclose: true,
  //       type,
  //     });
  //   }, 7000);
  // }
}

const baoBiaoDetailBack = (data) => {
  window.location.reload();
};

export { zeroReprot, zcfzbWrite, baoBiaoDetailBack };
